//
//  TradeListVC.swift
//  kxf
//
//  Created by Mac on 2024/3/20.
// TradeListTopVM

import Foundation
import MCToast
import MJRefresh
import UIKit

class TradeListVC: WHBaseViewVC {
    
    var pageNum = 1
    var pageSize = 10
    
    var dataSourceArray = NSMutableArray()
    var timeType = "start"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        sendDataQueryRequest()
    }
    lazy var topVm : TradeListTopVM = {
        let vm = TradeListTopVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: 0, height: 0))
        
        return vm
    }()
    lazy var filtVm : TradeListFilterVM = {
        let vm = TradeListFilterVM.init(frame: CGRect.init(x: 0, y: self.topVm.frame.maxY+kFitWidth(10), width: 0, height: 0))
        vm.timeLabel.text = "\(Date().getLast30Days())  -  \(Date().todayDate)"
        
        vm.tapBlock = {()in
            self.filtAlertVm.isHidden = false
        }
        return vm
    }()
    lazy var tipsLabel : UILabel = {
        let lab = UILabel.init(frame: CGRect.init(x: 0, y: self.filtVm.frame.maxY, width: SCREEN_WIDHT-kFitWidth(16), height: kFitWidth(30)))
        lab.textColor = .COLOR_TEXT_BLACK999
        lab.font = .systemFont(ofSize: 14, weight: .regular)
        lab.textAlignment = .right
        
        return lab
    }()
    lazy var tableView : UITableView = {
        let vi = UITableView.init(frame: CGRect.init(x: 0, y: self.tipsLabel.frame.maxY+kFitWidth(0), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(self.tipsLabel.frame.maxY+kFitWidth(0))), style: .plain)
        vi.delegate = self
        vi.dataSource = self
        vi.separatorStyle = .none
        vi.backgroundColor = .COLOR_LIGHT_GREY
        
        vi.register(SettleListTableViewCell.classForCoder(), forCellReuseIdentifier: "SettleListTableViewCell")
        
        if #available(iOS 11.0, *) {
            vi.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        
        vi.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.pageNum = 1
            self.sendDataQueryRequest()
        })

        vi.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            self.pageNum += 1
            self.sendDataQueryRequest()
        })
        
        return vi
    }()
    lazy var emptyView : EmptyViewWithBtn = {
        let emptyViewT = EmptyViewWithBtn.init(frame: CGRect.zero)
        emptyViewT.isHidden = true
        emptyViewT.contentLabel.text = "还没有记录~"
        
        return emptyViewT
    }()
    lazy var filtAlertVm : TradeListFilterAlertVM = {
        let vm = TradeListFilterAlertVM.init(frame: .zero)
        vm.isHidden = true
        vm.startTimeBtn.tapBlock = {()in
            self.timeType = "start"
            self.datePickerVm.isHidden = false
            self.datePickerVm.titleLabel.text = "选择查询开始日期"
            self.datePickerVm.datePicker.minimumDate = nil
        }
        vm.endTimeBtn.tapBlock = {()in
            self.timeType = "end"
            self.datePickerVm.isHidden = false
            self.datePickerVm.titleLabel.text = "选择查询结束日期"
            self.datePickerVm.datePicker.maximumDate = Date()
        }
        vm.queryBlock = {()in
            self.filtVm.timeLabel.text = "\(self.filtAlertVm.startTimeBtn.timeString)  -  \(self.filtAlertVm.endTimeBtn.timeString)"
            self.pageNum = 1
            self.sendDataQueryRequest()
        }
        return vm
    }()
    lazy var datePickerVm : DatePickerVM = {
        let vm = DatePickerVM.init(frame: .zero)
        vm.isHidden = true
        vm.timeConfirmBlock = {(time)in
            if self.timeType == "start"{
                self.filtAlertVm.startTimeBtn.timeLabel.text = "\(time)"
                self.filtAlertVm.startTimeBtn.timeString = "\(time)"
                self.timeType = "end"
                self.datePickerVm.isHidden = false
                self.datePickerVm.datePicker.minimumDate = Date().changeDateStringToDate(dateStr: time)
                self.datePickerVm.datePicker.maximumDate = Date()
                self.datePickerVm.titleLabel.text = "选择查询结束日期"
            }else{
                self.filtAlertVm.endTimeBtn.timeLabel.text = "\(time)"
                self.filtAlertVm.endTimeBtn.timeString = "\(time)"
            }
        }
        return vm
    }()
}

extension TradeListVC{
    func initUI() {
        initNavi(titleStr: "交易记录")
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        view.addSubview(topVm)
        view.addSubview(filtVm)
        view.addSubview(tipsLabel)
        
        view.addSubview(tableView)
        tableView.addSubview(emptyView)
        emptyView.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: self.tableView.frame.height*0.5)
        
        UIApplication.shared.keyWindow?.addSubview(filtAlertVm)
        UIApplication.shared.keyWindow?.addSubview(datePickerVm)
    }
}

extension TradeListVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        emptyView.isHidden = dataSourceArray.count > 0 ? true : false
        return dataSourceArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dict = self.dataSourceArray[indexPath.row] as? NSDictionary ?? [:]
        let cell = tableView.dequeueReusableCell(withIdentifier: "SettleListTableViewCell") as! SettleListTableViewCell
         cell.updateUIForTrade(dict: dict)
         
         return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kFitWidth(94)
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = TradeDetailVC()
        vc.tradeDict = self.dataSourceArray[indexPath.row] as? NSDictionary ?? [:]
        self.navigationController?.pushViewController(vc, animated: true)
    }
}


extension TradeListVC{
    func sendDataQueryRequest() {
        MCToast.mc_loading()
        let param = ["pageNum":"\(pageNum)",
                     "pageSize":"\(pageSize)",
                     "startTime":"\(self.filtAlertVm.startTimeBtn.timeString)",
                     "endTime":"\(self.filtAlertVm.endTimeBtn.timeString)",
                     "orderStatus":"\(self.filtAlertVm.statusString)",
                     "type":"\(self.filtAlertVm.payTypeString)"]
        WHNetworkUtil.shareManager().POST(urlString: "\(URL_trade_query)", parameters: param as [String:AnyObject],isNeedToast: true,vc:self) { responseObject in
            DLLog(message: "\(responseObject)")
            
            self.tableView.mj_footer!.endRefreshing()
            self.tableView.mj_header!.endRefreshing()
            
            let dataObj = responseObject["data"]as? NSDictionary ?? [:]
            let obj = dataObj["obj"]as? NSDictionary ?? [:]
            self.topVm.updateUI(dict: obj)
            
            self.tipsLabel.text = "共\(obj["tradeCount"]as? Int ?? 0)笔，\(WHUtils.convertStringToString("\(obj["totalAmount"]as? Double ?? 0.00)") ?? "0.00")元，\(obj["userNumber"]as? Int ?? 0)位顾客"
            
            if self.pageNum == 1{
                self.dataSourceArray.removeAllObjects()
            }
            
            let dataArr = dataObj["list"]as? NSArray ?? []
            // 提示没有更多数据
            if dataArr.count < self.pageSize {
                self.tableView.mj_footer!.endRefreshingWithNoMoreData()
            }
            
            self.dataSourceArray.addObjects(from: dataArr as! [Any])
            self.tableView.reloadData()
        }
    }
}
